package com.sunnada.edu.system.sysuser.service;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.sunnada.edu.system.pub.common.AppContext;
import com.sunnada.edu.system.pub.common.Common;
import com.sunnada.edu.system.pub.common.EXCELObject;
import com.sunnada.edu.system.pub.common.MD5;
import com.sunnada.edu.system.pub.common.RandomTool;
import com.sunnada.edu.system.pub.dao.PubDao;
import com.sunnada.edu.system.pub.service.RandomGUID;
import com.sunnada.edu.system.pub.util.DateUtil;
import com.sunnada.edu.system.pub.util.Utils;
import com.sunnada.edu.system.sysuser.dao.SysUserDao;

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {
	private static final Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);
	@Resource
	SysUserDao userDao;

	@Override
	public int getUserCots(HashMap<String, String> params) {
		return userDao.getUserCots(params);
	}

	@Override
	public List<?> findUsers(HashMap<String, String> params) {
		return userDao.findUsers(params);
	}

	@Override
	public String userDelete(HashMap<String, String> params) {
		String msg = "";
		int num = userDao.userDelete(params);
		if (num == 0) {
			msg = "删除失败!";
		}
		return msg;
	}

	@Override
	public String userAdd(HashMap<String, String> params) {
		String msg = "";
		int cot = SysUserMethods.getSysUserCotByPhone(params);
		if (cot > 0) {
			msg = "2";// 手机号已存在，请更换！
		} else {
			params.put("recId", UUID.randomUUID().toString());
			int num = userDao.userAdd(params);
			if (num == 0) {
				msg = "0";// 失败
			} else {
				msg = "1";// 成功
			}
		}

		return msg;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String userUpdate(HashMap<String, String> params) {
		String msg = "";
		int cot = SysUserMethods.getSysUserCotByPhone(params);
		if (cot > 0) {
			msg = "2";// 手机号已存在，请更换！
		} else {
			int num = userDao.userUpdate(params);
			if (num == 0) {
				msg = "0";// 失败
			} else {
				msg = "1";// 成功
			}
		}
		return msg;
	}

	@SuppressWarnings("unchecked")
	private void userEmployeeAndDeveloperAdd(HashMap<String, String> params) {
	}

	@Override
	public Map getUserByRecId(HashMap<String, String> params) {
		return userDao.getUserByRecId(params);
	}

	private String userRoleAdds(HashMap<String, String> params) {
		String userId = params.get("userId");
		String roleIds = params.get("roleIds");
		if (roleIds != null) {
			String s[] = roleIds.split(",");
			for (int i = 0; i < s.length; i++) {
				HashMap<String, String> param = new HashMap<String, String>();
				param.put("loginUserId", params.get("loginUserId"));
				param.put("roleId", s[i]);
				param.put("userId", userId);
				roleUserAdd(param);
			}
		}
		return null;
	}

	@Override
	public String roleUserAdd(HashMap<String, String> params) {
		int num = userDao.roleUserAdd(params);
		if (num == 0) {
			return "角色保存失败！";
		}
		return null;
	}

	@Override
	public String roleUserDelete(HashMap<String, String> params) {
		int num = userDao.roleUserDelete(params);
		return null;
	}

	@Override
	public String[] getRoleIdsByUserId(HashMap<String, String> params) {
		return userDao.getRoleIdsByUserId(params);
	}

	@Override
	public Map<String, String> getUser(HashMap<String, String> params) {
		return userDao.getUser(params);
	}

	@Override
	public String userpasswordUpdate(HashMap<String, String> params) {
		/*** 去掉非法字符 */
		String oldpassword = Utils.devExceptString(params.get("loginPwd"));
		String newpassword = Utils.devExceptString(params.get("newloginPwd"));
		/** 生成比对的密码 */
		oldpassword = MD5.md5(params.get("userId") + oldpassword);
		params.put("loginPwd", oldpassword);
		/** 查询密码信息 */
		Map userMap = getUser(params);
		/** 进行密码验证 */
		String msg = "";
		if (userMap == null) {
			msg = "输入的旧密码错误！";
		} else {
			newpassword = MD5.md5(params.get("userId") + newpassword); // 新密码加密生成
			params.put("loginPwd", newpassword);
			int num = userDao.userpasswordUpdate(params);
			if (num == 0) {
				msg = "修改失败！";
			}
		}
		return msg;
	}

	@Override
	public String userPwdReset(HashMap<String, String> params) {
		String userIds = params.get("userIds");
		if (userIds != null) {
			String s[] = userIds.split(",");
			for (int i = 0; i < s.length; i++) {
				HashMap<String, String> param = new HashMap<String, String>();
				param.put("userId", s[i]);
				String randpw = RandomTool.randNum(3) + "@" + RandomTool.randLetter(4);
				System.out.println("重置密码的账号:" + s[i] + "重置后的密码：" + randpw);
				logger.info("重置密码的账号:" + s[i] + "重置后的密码：" + randpw);
				String passWord = MD5.md5(s[i] + randpw);
				param.put("passWord", passWord);
				int num = userDao.userPwdReset(param);
				if (num == 0) {
					return "重置密码失败！";
				} else {
					// 发送短信
					Map user = getUserByUserIdNotStatus(param);
					String tel = (String) user.get("TEL");
					String smessage = "已成功为您的集客展业系统登录账号：" + s[i] + "重置密码,重置后密码：" + randpw + ",请及时登录并修改密码。【集客展业】";// 短信内容
					String id = new RandomGUID().toString();// 验证码流水
				}
			}
		}
		return null;
	}

	public Map getUserByUserIdNotStatus(HashMap<String, String> params) {
		return userDao.getUserByUserIdNotStatus(params);
	}

	@Override
	public String userEnable(HashMap<String, String> params) {
		String msg = "";
		int num = userDao.userEnable(params);
		if (num == 0) {
			msg = "启用失败！";
		}
		return msg;
	}

	@Override
	public String userDisable(HashMap<String, String> params) {
		String msg = "";
		int num = userDao.userDisable(params);
		if (num == 0) {
			msg = "停用失败！";
		}
		return msg;
	}

	@Override
	public String userLogout(HashMap<String, String> params) {
		String msg = "";
		int num = userDao.userLogout(params); // 修改用户表的rec_status状态
		if (num == 0) {
			msg = "注销失败！";
		}/*
		 * else{ userDao.roleUseLogout(params); //修改角色用户表的rec_status状态
		 * userDao.userRoleAuthorizeLogout(params); //修改用户授权表的rec_status 状态 }
		 */
		return msg;
	}

	@Override
	public String[] getAuthorizeRoleIdsByUserId(HashMap<String, String> params) {
		return userDao.getAuthorizeRoleIdsByUserId(params);
	}

	@Override
	public String userRoleAuthorizeUpdate(HashMap<String, String> params) {
		String msg = "";
		msg = userRoleAuthorizeDelete(params); // 先删除数据 userId
		if (msg == null) {
			msg = userRoleAuthorizeAdds(params); // 在添加
		}
		return msg;
	}

	private String userRoleAuthorizeAdds(HashMap<String, String> params) {
		String roleIds = params.get("roleIds");
		String userId = params.get("userId");
		if (roleIds != null) {
			String s[] = roleIds.split(",");
			for (int i = 0; i < s.length; i++) {
				HashMap<String, String> param = new HashMap<String, String>();
				param.put("userId", userId);
				param.put("roleId", s[i]);
				userRoleAuthorizeAdd(param);
			}
		}
		return null;
	}

	private String userRoleAuthorizeAdd(HashMap<String, String> param) {
		int num = userDao.userRoleAuthorizeAdd(param);
		if (num == 0) {
			return "保存失败！";
		}
		return null;
	}

	private String userRoleAuthorizeDelete(HashMap<String, String> params) {
		int num = userDao.userRoleAuthorizeDelete(params);
		return null;
	}

	@Override
	public String userRoleBind(HashMap<String, String> params) {
		String msg = "";
		msg = userRoleBindDelete(params); // 先删除数据
		if (msg == null) {
			msg = userRoleBindAdds(params); // 在添加
		}
		return msg;
	}

	private String userRoleBindDelete(HashMap<String, String> params) {
		int num = userDao.userRoleBindDelete(params);
		return null;
	}

	private String userRoleBindAdds(HashMap<String, String> params) {
		String userRoleIds = params.get("userRoleIds"); // 获取要绑定的角色的Id
		String userId = params.get("userId");
		if (userRoleIds != null) {
			String s[] = userRoleIds.split(",");
			for (int i = 0; i < s.length; i++) {
				HashMap<String, String> param = new HashMap<String, String>();
				param.put("userId", userId);
				param.put("roleId", s[i]);
				userRoleBindAdd(param);
			}
		}
		return null;
	}

	private String userRoleBindAdd(HashMap<String, String> param) {
		int num = userDao.userRoleBindAdd(param);
		if (num == 0) {
			return "保存失败！";
		}
		return null;
	}

	@Override
	public String[] getNoExitRoleIds(HashMap<String, String> params) {
		return userDao.getNoExitRoleIds(params);
	}

	@Override
	public String[] getNotAuthorizeRoleIdsByUserId(HashMap<String, String> params) {
		return userDao.getNotAuthorizeRoleIdsByUserId(params);
	}

	@Override
	public String resetPwd(HashMap<String, String> params) {
		String userIds = params.get("recIds");
		if (userIds != null) {
			String s[] = userIds.split(",");
			for (int i = 0; i < s.length; i++) {
				HashMap<String, String> param = new HashMap<String, String>();
				param.put("userId", s[i]);
				String phone = s[i];
				String pwd = phone.substring(phone.length() - 6, phone.length());
				String passWord = MD5.md5(s[i] + pwd);
				param.put("passWord", passWord);
				int num = userDao.userPwdReset(param);
				// 发送短信
				String smessage = "已成功为您系统登录账号：" + s[i] + "重置密码,重置后密码：" + pwd + ",请及时登录并修改密码。【智慧家校】";// 短信内容

			}
		}
		return "密码重置成功！重置后的密码为手机号末尾六位";
	}

	@Override
	public List<HashMap<String, String>> getMyRoleList(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		// 下载失败的节目单集合---对应终端
		String loginUserId = params.get("loginUserId");
		String loginSchoolId = params.get("loginSchoolId");
		String sql = " SELECT distinct r.REC_ID, r.ROLE_NAME  " + "from  S_SYSROLEUSER t    "
				+ "left join  s_sysrole r on  r.REC_ID = t.ROLE_ID " + "WHERE  t.USER_ID = '" + loginUserId + "'  and r.school_id='"
				+ loginSchoolId + "'";
		return (List<HashMap<String, String>>) dao.selectList(sql);

	}

	@Override
	public String grentRoleToUser(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String loginUserId = params.get("loginUserId");
		String userId = params.get("userId");
		String roleIds = params.get("roleIds");
		String s[] = roleIds.split(",");

		String sql = "delete from S_SYSROLEUSER where USER_ID='" + userId + "'";
		dao.delete(sql);
		for (int i = 0; i < s.length; i++) {
			String recId = UUID.randomUUID().toString();
			HashMap<String, String> param = new HashMap<String, String>();
			sql = "insert into S_SYSROLEUSER(REC_ID,ROLE_ID,USER_ID,REC_PERSON,REC_TIME)  " + "values('"+recId+"','" + s[i] + "','"
					+ userId + "','" + loginUserId + "',now())";
			dao.insert(sql);
		}

		// 终止权限传递
		String roleLost = params.get("roleLost");
		if (Utils.isNotNull(roleLost)) {
			roleLost = Utils.getSqlSplitStr(roleLost);
			sql = " delete from s_sysroleuser where ROLE_ID in(" + roleLost + ") and REC_PERSON='" + userId + "'";
			dao.delete(sql);
		}

		return "";
	}

	@Override
	public List getSelectUserRole(HashMap<String, String> params) {
		PubDao dao = AppContext.getInstance().getPubDao();
		String userId = params.get("userId");
		String schoolId = params.get("schoolId");
		String sql = " SELECT DISTINCT R.REC_ID, R.ROLE_NAME  " + "FROM  S_SYSROLEUSER T    "
				+ " LEFT JOIN  S_SYSROLE R ON  R.REC_ID = T.ROLE_ID " + " WHERE  T.USER_ID = '" + userId + "'";
		return (List<HashMap<String, String>>) dao.selectList(sql);
	}

	@Override
	public String userEnables(HashMap<String, String> params) {
		String msg = "";
		int num = userDao.userEnables(params);
		if (num > 0) {
			msg = "1";
		} else {
			msg = "0";
		}
		return msg;
	}

	@Override
	public String userDisables(HashMap<String, String> params) {
		String msg = "";
		int num = userDao.userDisables(params);
		if (num > 0) {
			msg = "1";
		} else {
			msg = "0";
		}
		return msg;
	}

	@Override
	public void exportSysUser(HashMap<String, String> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
		List dataList = userDao.exportSysUser(params);
		String recId = UUID.randomUUID().toString();
		String realPath = request.getSession().getServletContext().getRealPath("/file/temp");
		EXCELObject s = new EXCELObject();
		s.seteFilePath(realPath);
		String[] titH = { "用户手机号", "姓名", "用户类型" };
		String[] titN = { "PHONE", "USER_NAME", "USER_TYPE_CHAR" };
		s.setFname("系统用户 "); // 临时文件名
		s.setTitle("系统用户"); // 大标题名称
		s.setTitH(titH);
		s.setTitN(titN);
		s.setDataList(dataList);
		File exportFile = null;
		exportFile = s.setData();
		String excelName = "系统用户" + DateUtil.getCurrentTime() + ".xls";
		s.exportExcel("系统用户", excelName, exportFile, request, response);

	}

	@Override
	public void sysUserImport(MultipartFile file,HashMap<String, String> params,
			HttpServletRequest request, HttpServletResponse response)throws Exception {
		boolean version = false;
		InputStream is = null;
		is = file.getInputStream();
		Workbook wb = null;
		if (version) {
			wb = new XSSFWorkbook(is);
		} else {
			wb = new HSSFWorkbook(is);
		}
		Sheet sheet = wb.getSheetAt(0);
		ArrayList<Map<String, String>> dataList = new ArrayList<Map<String, String>>();//错误的临时存放列表
		for (int i = 2; i <= sheet.getLastRowNum(); i++) {
			Row row = sheet.getRow(i);
			if (row == null) { // 最后行为空的时候
				continue;
			}
			String sysUserName = getValueFromCell(row.getCell(1)); // 姓名
			Map<String, String> sysUser = new HashMap<String, String>();
			sysUser.put("USER_NAME", sysUserName);
			dataList.add(sysUser);
		}

		//String recId = UUID.randomUUID().toString();
		String realPath = request.getSession().getServletContext()
				.getRealPath("/file/temp");
		EXCELObject s = new EXCELObject();
		s.seteFilePath(realPath);
		String[] titH = { "姓名" };
		String[] titN = { "USER_NAME"};
		s.setFname("错误系统用户 "); // 临时文件名
		s.setTitle("错误系统用户"); // 大标题名称
		s.setTitH(titH);
		s.setTitN(titN);
		s.setDataList(dataList);
		File exportFile = null;
		exportFile = s.setData();
		String excelName = "错误系统用户" + DateUtil.getCurrentTime() + ".xls";
		s.exportExcel("错误系统用户", excelName, exportFile, request, response);

	}

	public static final String getValueFromCell(Cell cell) {
		if (cell == null) {
			return "";
		}
		cell.setCellType(Cell.CELL_TYPE_STRING);
		String value = null;
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_NUMERIC: // 数字
			value = String.valueOf(cell.getNumericCellValue());
			break;
		case Cell.CELL_TYPE_STRING: // 字符串
			value = cell.getStringCellValue();
			break;
		case Cell.CELL_TYPE_FORMULA: // 公式
			// 用数字方式获取公式结果，根据值判断是否为日期类型
			double numericValue = cell.getNumericCellValue();
			value = String.valueOf(numericValue);
			break;
		case Cell.CELL_TYPE_BLANK: // 空白
			value = StringUtils.EMPTY;
			break;
		case Cell.CELL_TYPE_BOOLEAN: // Boolean
			value = String.valueOf(cell.getBooleanCellValue());
			break;
		case Cell.CELL_TYPE_ERROR: // Error，返回错误码
			value = String.valueOf(cell.getErrorCellValue());
			break;
		default:
			value = StringUtils.EMPTY;
			break;
		}
		return value;
	}
	
	
	@Override
	public void sysUserModelExport(HashMap<String, String> params,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ArrayList<Map<String, String>> dataList = new ArrayList<Map<String, String>>();//错误的临时存放列表
		Map<String, String> sysUser = new HashMap<String, String>();
		sysUser.put("USER_NAME", "张三");
		dataList.add(sysUser);
		String recId = UUID.randomUUID().toString();
		String realPath = request.getSession().getServletContext()
				.getRealPath("/file/temp");
		EXCELObject s = new EXCELObject();
		s.seteFilePath(realPath);
		String[] titH = {"姓名" };
		String[] titN = {"USER_NAME"};
		s.setFname("学生信息模板"); // 临时文件名
		s.setTitle("学生信息模板"); // 大标题名称
		s.setTitH(titH);
		s.setTitN(titN);
		s.setDataList(dataList);
		File exportFile = null;
		exportFile = s.setData();
		String excelName = "系统用户" + DateUtil.getCurrentTime() + ".xls";
		s.exportExcel("系统用户", excelName, exportFile, request, response);

	}

	@Override
	public List<?> getRolePower(HashMap<String, String> params) {
		return userDao.getRolePower(params);
	}
}
